/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.domain.dao.category;

import com.david.documentation.domain.dao.AbstractDAO;
import com.david.documentation.domain.entities.category.Category;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Repository(value = "categoryDao")
public class CategoryDaoImpl extends AbstractDAO<Category> implements CategoryDao {

	@PersistenceContext
    private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Class<Category> getClazz() {
		return Category.class;
	}

	public boolean checkforDublicate(String name) {
		Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name = :aName");
        query.setParameter("aName", name);
        return query.getResultList().size() > 0;
	}

	public Category findCategoryByName(String name) {
		Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name = :aName");
        query.setParameter("aName",name);
		return (Category)query.getSingleResult();
	}

	public List<Category> findCategorysByName(String name) {
		Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.name LIKE :aName");
        query.setParameter("aName","%" + name + "%");
		query.setMaxResults(3);
		return query.getResultList();
	}

	public Number getNumberOfDokus(Long catId) {
		javax.persistence.Query query = getEntityManager().createNativeQuery("SELECT COUNT(*) FROM category,CATEGORY_DOKU WHERE CATEGORY_DOKU.CATEGORY_ID =category.CATEGORY_ID AND category.CATEGORY_ID = :aName");
        query.setParameter("aName", catId );
		return (Number)query.getSingleResult();
	}

}
